<template>
  <div class="search">
    <el-select
        v-model="selectVal"
        filterable
        remote
        clearable
        placeholder="请选择.."
        :remote-method="remoteMethod"
        :loading="loading"
        style="width: 240px"
    >
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
  </div>
</template>
<script setup lang="ts">
import {onMounted, ref, defineProps, defineEmits, computed, toRefs} from 'vue'
import API from '../api/select'
interface ListItem {
  value: string
  label: string
}
const list = ref<ListItem[]>([])
const options = ref<ListItem[]>([])
const loading = ref(false)
//props start
const props = defineProps({
  value: {
    required: true
  },
  action: {
    type: String
  },
  query: {}
})
const { action } = toRefs(props)
const emits = defineEmits(['update:value'])
const selectVal = computed({
  get:() => props.value,
  set: (val) => {
    emits('update:value', val)
  }
})
let states:any = [
  'Alabama',
  'Alaska',
  'Arizona',
  'Arkansas',
  'California',
  'Colorado',
  'Connecticut',
  'Delaware',
  'Florida',
]
onMounted(() => {
  // API.option({ action }).then(res => {
  //   let resArr = res.data.data
  //  const newArr = resArr.map((item:any) => ({ id: item.id, name: item.name }))
  //   states = toRefs(newArr)
  // }).finally(() =>{
  //   list.value = states.map((item:any) => {
  //     console.log(item,8852)
  //     return { value: `value:${item.value.id}`, label: `${item.value.name}` }
  //   })
  // })
})

const remoteMethod:any = (query: string) => {
  console.log(query)
  if (query) {
    loading.value = true
    API.option({ action, name: query }).then(res => {
      let resArr = res.data.data
      const newArr = resArr.map((item:any) => ({ id: item.id, name: item.name }))
      states = toRefs(newArr)
    }).finally(() =>{
      list.value = states.map((item:any) => {
        return { value: `value:${item.value.id}`, label: `${item.value.name}` }
      })
      loading.value = false
      options.value = list.value.filter((item) => {
        return item.label.toLowerCase().includes(query.toLowerCase())
      })
    })
  } else {
    options.value = []
  }
}


</script>
<style scoped>
</style>